var CreateOutReturnorder = function () {
  var template = /*html*/ `
    <div class="create-out-returnorder" v-loading.fullscreen.lock="loading">
      <div class="title" style="text-align:center;font-size:20px;margin-bottom:20px;">外协单返回</div>
      <el-form :model="returnOrder" label-width="100px">
        <el-form-item label="订单编号">
          <page-select filterable v-if="canSelectOrder" :options="orderList" v-model="returnOrder.orderId" class="form-input" :disabled="orderLoading"
            value-field="orderId" label-field="orderId" popper-class="orderSelectPopover" :filter-method="orderFilterMehod"
            @change="orderChange">
            <template slot-scope="scope">
              <el-option v-for="order in scope.options" :key="order.orderId" :value="order.orderId" :label="order.orderId">
                <div class="return-order-select-item">
                  <span style="width:145px;">{{order.orderId}}</span>
                  <span style="min-width:145px;">{{order.companyOrderId}}</span>
                  <span style="min-width:100px;">{{order.factoryId}}</span>
                  <span style="min-width:50px;">{{order.customerId}}</span>
                </div>
              </el-option>
            </template>
          </page-select>
          <span v-else>{{returnOrder.orderId}}</span>
        </el-form-item>

        <template v-if="selectOrder!==null">
        <el-form-item label="公司订单编号">
          <span>{{selectOrder.companyOrderId}}</span>
        </el-form-item>
        <el-form-item label="工厂型号">
          <span>{{selectOrder.factoryId}}</span>
        </el-form-item>
        <el-form-item label="客户型号">
          <span>{{selectOrder.customerId}}</span>
        </el-form-item>
        </template>

        <el-form-item label="供应商">
          <el-select filterable v-model="returnOrder.supplierId" class="form-input" :loading="orderLoading" @change="supplierChange">
            <el-option v-for="supplier in supplierList" :key="supplier.supplierId" :value="supplier.supplierId" :label="supplier.supplierName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加工工艺">
          <el-select filterable v-model="returnOrder.technology" class="form-input" :loading="orderLoading" @change="technologyChange">
            <el-option v-for="(technology,index) in getTechnologyList()" :key="'technology_'+index" :value="technology"
              :label="technology"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加工对象">
          <el-select filterable v-model="returnOrder.maching" class="form-input" :loading="orderLoading" @change="machingChange">
            <el-option v-for="(maching,index) in getMachingList()" :key="'maching_'+index" :value="maching.value" :label="maching.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="返回颜色数量" v-if="returnOrder.colorObj.length>0">
          <table class="colorCountTable" cellspacing="0" cellpadding="0">
          <tr class="colorCountTable-head" style="text-align:center">
            <td style="width:20px;"></td>
            <td style="padding-right:5px;">颜色</td>
            <td style="min-width:130px;padding-right:5px;">数量(付)</td>
            <td style="min-width:150px;padding-right:5px;">计价数量</td>
            <td style="min-width:130px;">单价</td>
          </tr>
            <template v-for="(orderColorList,typeIndex) in returnOrder.colorObj">
            <template v-for="(color,outIndex) in orderColorList">
            <template v-for="(detailColor,index) in color.detailColors">
              <tr :key="'colorCount_'+typeIndex+'_'+outIndex+'_'+index">
                <td>
                  <el-checkbox v-model="color.checked" v-if="color.hasCheck"></el-checkbox>
                </td>
                <td>
                  <div style="line-height:16px;">{{detailColor.showColor}}</div>
                </td>
                <td>
                  <div v-if="!color.hasCheck" class="display-text">
                    {{getAllCount(orderColorList,color,'count')}}
                  </div>
                  <el-input-number v-else v-model="color.count" :min="1" :max="color.total" controls-position="right" size="medium"
                    style="width:100%;max-width:130px;" :disabled="!color.checked" :precision="0" @change="handleCountChange(color)">
                  </el-input-number>
                </td>
                <td>
                  <template v-if="color.hasCheck">
                    <el-input-number is-decimal-zero v-model="color.valuationCount" :min="1/Math.pow(10,color.precision)" :max="color.maxValuationCount" 
                      controls-position="right" size="medium" style="width:100%;max-width:130px;" :disabled="!color.checked||color.valuationUint==='付'"
                      :precision="color.precision">
                    </el-input-number>
                    <span>{{color.valuationUint}}</span>
                  </template>
                </td>
                <td>
                  <el-input-number v-if="color.hasCheck" v-model="color.unitPrice" :min="0" :max="99999999.99" controls-position="right"
                    size="medium" style="width:100%;max-width:130px;" :disabled="!color.checked||!color.canUpdatePrice" :precision="2" placeholder="单价"></el-input-number>
                </td>
              </tr>
            </template>
            </template>
            <tr style="height:10px;" :key="'line'+typeIndex" v-if="typeIndex!==returnOrder.colorObj.length-1">
              <td colspan="5">
                <div class="table-line"></div>
              </td>
            </tr>
            </template>
          </table>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="returnOrder.remark" class="textarea-autosize" type="textarea" :autosize="true" resize="none" :maxlength="50"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        <el-button type="primary" @click="save(false)">生成外协返回单</el-button>
        <el-button :disableld="!hasApproval" type="primary" @click="save(true)">审核过账</el-button>
      </div>
    </div>
  `;

  return {
    props: {
      outOrder: Object
    },

    data: function () {
      return {
        loading: false,
        orderLoading: false,
        canSelectOrder: this.outOrder === undefined,
        orderList: [],
        outOrderList: [],
        supplierList: [],
        materialMachingMap: {},
        returnOrder: this.getInitReturnOrder(),
        selectOrder: null,
        SysUtil: SysUtil,
        hasApproval: false
      };
    },
    created: function () {
      var self = this;
      Promise.all([
        this.checkApprovalAuthority(),
        this.setMaterialMachingMap(),
        this.setOrderList()
      ]).then(function () {
        self.orderChange();
        if (!self.canSelectOrder) {
          self.setReturnOrderData();
        }
      }).catch(function () {});
    },
    methods: {
      getInitReturnOrder() {
        var outOrder = this.outOrder;
        var orderId;
        if (outOrder === undefined) {
          orderId = '';
        } else {
          orderId = outOrder.orderId;
        }
        return {
          orderId: orderId,
          supplierId: '',
          technology: '',
          maching: '',
          colorObj: [],
          remark: ''
        };
      },

      checkApprovalAuthority: function () {
        var self = this;
        return ajaxRequest('putOutNew/checkPutOutApprovalPermission', {}, false).then(function (res) {
          var hasApproval = res.result;
          self.hasApproval = hasApproval;
          return hasApproval;
        });
      },

      setReturnOrderData: function () {
        var returnOrder = this.returnOrder;
        var outOrder = this.outOrder;
        returnOrder.supplierId = outOrder.supplierId;
        returnOrder.technology = outOrder.technology;

        var maching = outOrder.maching;
        if (!SysUtil.isEmpty(maching)) {
          var type = outOrder.type;
          if (type !== 0) {
            if (type === -1) {
              maching = 'all'
            } else {
              var materialMachingMap = this.materialMachingMap;
              for (var key in materialMachingMap) {
                if (materialMachingMap[key] === maching) {
                  maching = `machineMap-${key}`;
                }
              }
            }
          }
          returnOrder.maching = maching;
          this.machingChange();
        }
      },

      setMaterialMachingMap: function () {
        this.loading = true;
        var self = this;
        return ModuleUtil.getMaterialMachingMap().then(function (materialMachingMap) {
          self.materialMachingMap = materialMachingMap;
          self.loading = false;
          return materialMachingMap;
        }).catch(function () {
          self.loading = false;
          return {};
        });
      },

      setOrderList: function () {
        this.orderLoading = true;
        var self = this;
        return ajaxRequest('putOutNew/getPutoutOrder', {
          isFinish: 2,
          status: 1
        }).then(function (res) {
          var outOrderList = res.returnData;
          self.outOrderList = outOrderList;

          var orderList = self.getListFromOutOrderList({
            uniqFun: 'orderId',
            dataMapFun: function (order) {
              return {
                orderId: order.orderId,
                coustomOrderId: order.coustomOrderId,
                factoryId: order.factoryId,
                customerId: order.coustomId
              };
            }
          });
          self.orderList = orderList;
          self.supplierList = [];
          self.returnOrder.supplierId = '';
          self.returnOrder.technology = '';
          self.returnOrder.maching = '';
          self.returnOrder.colorObj = [];
          self.orderLoading = false;
        }).catch(function () {
          self.orderLoading = false;
        });
      },

      getListFromOutOrderList: function (option) {
        var orderList = this.outOrderList;

        var filterFun = option.filterFun;
        if (filterFun !== undefined) {
          orderList = _.filter(orderList, filterFun);
        }

        var dataMapFun = option.dataMapFun;
        if (dataMapFun !== undefined) {
          orderList = _.map(orderList, dataMapFun);
        }

        if (typeof dataMapFun === 'string') {
          orderList = _.uniq(orderList);
        } else {
          var uniqFun = option.uniqFun;
          if (uniqFun !== undefined) {
            orderList = _.uniqBy(orderList, uniqFun);
          }
        }

        return orderList;
      },

      orderChange: function () {
        var returnOrder = this.returnOrder;

        var orderList = this.orderList;
        var orderId = returnOrder.orderId;
        if (orderId !== '') {
          var selectOrder = _.find(orderList, {
            orderId: returnOrder.orderId
          });
          this.selectOrder = selectOrder;
        }

        var supplierList = this.getListFromOutOrderList({
          filterFun: {
            orderId: returnOrder.orderId
          },
          dataMapFun: function (order) {
            return {
              supplierId: order.supplierId,
              supplierName: order.supplierName
            };
          },
          uniqFun: 'supplierId'
        });
        this.supplierList = supplierList;
        returnOrder.supplierId = '';
        returnOrder.technology = '';
        returnOrder.maching = '';
        returnOrder.colorObj = [];
      },

      supplierChange: function () {
        var returnOrder = this.returnOrder;
        returnOrder.technology = '';
        returnOrder.maching = '';
        returnOrder.colorObj = [];
      },

      technologyChange: function () {
        var returnOrder = this.returnOrder;
        returnOrder.maching = '';
        returnOrder.colorObj = [];
      },

      machingChange: function () {
        var returnOrder = this.returnOrder;
        var maching = returnOrder.maching;

        var type;
        if (maching === 'all') {
          type = -1;
        } else if (maching.indexOf('machineMap-') === 0) {
          type = maching.split('-')[1];
          type = Number(type);
        } else {
          type = 0;
        }

        var fields = ['orderId', 'supplierId', 'technology'];
        var colorList = this.getListFromOutOrderList({
          filterFun: function (obj) {
            if (type !== obj.type) {
              return false;
            }

            for (var i = 0; i < fields.length; i++) {
              var field = fields[i];
              if (obj[field] !== returnOrder[field]) {
                return false;
              }
            }

            if (type === 0) {
              return obj.maching === maching;
            }
            return true;
          },
          dataMapFun: function (order) {
            var additionalMaterialType = order.additionalMaterialType;
            var color = order.color;
            if (additionalMaterialType !== '') {
              color = order.additionalColor;
            }
            return {
              id: order.id,
              color: color,
              count: order.count,
              valuationCount: order.valuationCount,
              valuationUint: order.valuationUint,
              maching: order.maching,
              rowIndex: order.rowIndex,
              canUpdatePrice: order.isCanUpdatePrice,
              unitPrice: order.unitPrice,
              additionalMaterialType: additionalMaterialType,
              additionalRowIndex: order.additionalRowIndex,
              typeId: order.typeId
            };
          }
        });

        var colorGroup = _.groupBy(colorList, 'typeId');
        var colorObj = {};
        if (type !== 0) {
          for (var typeId in colorGroup) {
            colorObj[typeId] = this.getFrameColorList(colorGroup[typeId]);
          }
        } else {
          for (var typeId in colorGroup) {
            colorObj[typeId] = this.getNormalColorList(colorGroup[typeId]);
          }
        }

        var colors = [];
        for (var typeId in colorObj) {
          colors.push(colorObj[typeId]);
        }
        returnOrder.colorObj = colors;
      },

      getFrameColorList: function (colorList) {
        var colorGroup = _.groupBy(colorList, 'rowIndex');
        var flag = SysUtil.getObjectFieldCount(colorGroup) === 1;
        var colors = [];
        for (var rowIndex in colorGroup) {
          var details = colorGroup[rowIndex];
          var maxDetail = _.minBy(details, 'count');
          var maxCount = maxDetail.count;
          var maxValuationDetail = _.minBy(details, 'valuationCount');
          var maxValuationCount = maxValuationDetail.valuationCount;
          var detailColors = [];
          for (var i = 0; i < details.length; i++) {
            var obj = details[i];
            var color = obj.color;
            if (color === null) {
              color = '';
            }
            var showColor = `${color}(${obj.maching})`;
            detailColors.push({
              id: obj.id,
              color: color,
              showColor: showColor,
              materialType: obj.maching,
              additionalMaterialType: obj.additionalMaterialType,
              additionalRowIndex: obj.additionalRowIndex,
              typeId: obj.typeId
            });
          }

          var hasCheck = flag || rowIndex !== '-1';
          var valuationUint = details[0].valuationUint;
          var precision = SysUtil.getMaterialNumberPrecision(valuationUint, 4);

          colors.push({
            count: maxCount,
            total: maxCount,
            valuationCount: maxValuationCount,
            maxValuationCount: maxValuationCount,
            valuationUint: valuationUint,
            precision: precision,
            checked: false,
            hasCheck: hasCheck,
            canUpdatePrice: details[0].canUpdatePrice,
            unitPrice: details[0].unitPrice,
            rowIndex: rowIndex,
            detailColors: detailColors
          });
        }
        colors = _.orderBy(colors, [function (color) {
          var rowIndex = Number(color.rowIndex);
          return rowIndex;
        }]);
        return colors;
      },

      getNormalColorList: function (colorList) {
        var colors = [];
        for (var i = 0; i < colorList.length; i++) {
          var color = colorList[i];

          var valuationUint = color.valuationUint;
          var precision = SysUtil.getMaterialNumberPrecision(valuationUint, 4);
          var obj = {
            count: color.count,
            total: color.count,
            valuationCount: color.valuationCount,
            maxValuationCount: color.valuationCount,
            valuationUint: valuationUint,
            precision: precision,
            rowIndex: color.rowIndex,
            checked: false,
            hasCheck: true,
            canUpdatePrice: color.canUpdatePrice,
            unitPrice: color.unitPrice,
            detailColors: [{
              id: color.id,
              color: color.color,
              showColor: color.color,
              materialType: color.maching,
              additionalMaterialType: color.additionalMaterialType,
              additionalRowIndex: color.additionalRowIndex,
              typeId: color.typeId
            }]
          };
          colors.push(obj);
        }
        colors = _.orderBy(colors, [function (color) {
          var rowIndex = Number(color.rowIndex);
          return rowIndex;
        }]);
        return colors;
      },

      getTechnologyList: function () {
        var returnOrder = this.returnOrder;
        var technologyList = this.getListFromOutOrderList({
          filterFun: {
            orderId: returnOrder.orderId,
            supplierId: returnOrder.supplierId
          },
          dataMapFun: 'technology'
        });

        return technologyList;
      },

      getMachingList: function () {
        var returnOrder = this.returnOrder;
        var orderList = this.getListFromOutOrderList({
          filterFun: {
            orderId: returnOrder.orderId,
            supplierId: returnOrder.supplierId,
            technology: returnOrder.technology
          },
          dataMapFun: function (obj) {
            return {
              maching: obj.maching,
              type: obj.type
            };
          }
        });

        var orderGroup = _.groupBy(orderList, 'type');

        var machingList = [];
        if (orderGroup[-1] !== undefined) {
          machingList.push[{
            value: 'all',
            label: '整架'
          }];
        }

        var materialMachingMap = this.materialMachingMap;
        for (var key in materialMachingMap) {
          if (orderGroup[key] === undefined) {
            continue;
          }
          machingList.push({
            value: 'machineMap-' + key,
            label: materialMachingMap[key]
          });
        }

        var addMachingList = orderGroup[0];
        if (addMachingList !== undefined) {
          addMachingList = _.map(addMachingList, function (obj) {
            return {
              value: obj.maching,
              label: obj.maching
            };
          });
          addMachingList = _.uniqBy(addMachingList, 'value');
          machingList.pushArray(addMachingList);
        }
        return machingList;
      },

      save: function (isAduit) {
        var returnOrder = this.returnOrder;
        var postData = this.getReturnOrderObject(returnOrder);
        if (postData === null) {
          return;
        }

        var maching = returnOrder.maching;
        var type;
        if (maching === 'all') {
          type = -1;
        } else if (maching.indexOf('machineMap-') === 0) {
          type = maching.split('-')[1];
          type = Number(type);
        } else {
          type = 0;
        }
        var remark = returnOrder.remark;
        postData = _.map(postData.colorList, function (color) {
          var typeId = color.typeId;
          if (typeId === undefined) {
            typeId = null;
          }

          obj = {
            id: color.id,
            returnCount: color.count,
            valuationCount: color.valuationCount,
            rowIndex: color.rowIndex,
            unitPrice: color.unitPrice,
            additionalMaterialType: '',
            additionalRowIndex: '',
            type: type,
            typeId: typeId,
            remark: remark
          };

          var additionalMaterialType = color.additionalMaterialType;
          if (!SysUtil.isEmpty(additionalMaterialType)) {
            obj.additionalMaterialType = additionalMaterialType;
            obj.additionalRowIndex = color.additionalRowIndex;
            obj.typeId = color.additionalRowIndex;
          }
          return obj;
        });

        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/returnPutOutOrder', {
          returnPutoutOrderArray: JSON.stringify(postData),
          isAduit: isAduit
        }).then(function () {
          self.loading = false;
          self.$alert('外协单返回保存成功', '信息', {
            callback: function () {
              if (self.canSelectOrder) {
                self.returnOrder = self.getInitReturnOrder();
                self.selectOrder = null;
                self.supplierList = [];
              }
              self.$emit('save-success', returnOrder);
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      getReturnOrderObject: function (returnOrder) {
        var postData = {};
        var checkFields = ["orderId", "supplierId", "technology", "maching"];
        for (var i = 0; i < checkFields.length; i++) {
          var field = checkFields[i];
          var value = returnOrder[field];
          if (value === undefined || value === null || value === '') {
            var msg = this.getErrorMsg(field);
            this.$alert(msg, '提示');
            return null;
          } else {
            postData[field] = value;
          }
        }

        var colorObj = returnOrder.colorObj;
        var colorCount = [];
        for (var i = 0; i < colorObj.length; i++) {
          var colorList = this.getOrderColorList(colorObj[i]);
          if (typeof colorList === 'string') {
            continue;
          }
          colorCount.pushArray(colorList);
        }

        postData.colorList = colorCount;
        return postData;
      },

      getOrderColorList: function (colorList) {
        var checkedColorList = _.filter(colorList, {
          checked: true
        });
        if (checkedColorList.length === 0) {
          return 'color';
        }

        var maching = this.returnOrder.maching;
        if (maching === 'all' || maching.indexOf('machineMap-') === 0) {
          var allColorList = _.filter(colorList, {
            hasCheck: false
          });
          var allColors = [];
          for (var i = 0; i < allColorList.length; i++) {
            var list = _.map(checkedColorList, function (obj) {
              var allColor = _.cloneDeep(allColorList[i]);
              allColor.count = obj.count;
              allColor.valuationCount = obj.valuationCount;
              allColor.typeId = obj.rowIndex;
              allColor.unitPrice = obj.unitPrice;
              allColor.noCheckValid = true;
              return allColor;
            });
            allColors.pushArray(list);
          }
          checkedColorList.pushArray(allColors);
        }

        var colorCount = [];
        for (var i = 0; i < checkedColorList.length; i++) {
          var color = checkedColorList[i];
          if (!this.checkColorValid(color)) {
            return '';
          }

          var detailColors = color.detailColors;
          for (var j = 0; j < detailColors.length; j++) {
            var detailColor = detailColors[j];
            var obj = {
              id: detailColor.id,
              count: color.count,
              valuationCount: color.valuationCount,
              rowIndex: color.rowIndex,
              unitPrice: color.unitPrice
            }

            var additionalMaterialType = detailColor.additionalMaterialType;
            if (!SysUtil.isEmpty(additionalMaterialType)) {
              obj.additionalMaterialType = additionalMaterialType;
              obj.additionalRowIndex = detailColor.additionalRowIndex;
            }

            var typeId = color.typeId;
            if (typeId !== undefined) {
              obj.typeId = typeId;
            }
            colorCount.push(obj);
          }
        }
        return colorCount;
      },

      checkColorValid: function (color) {
        if (color.noCheckValid) {
          return true;
        }

        var feilds = ['count', 'valuationCount', 'unitPrice'];
        var flag = CheckVaildUtil.checkNullValue(feilds, color, this.getErrorMsg);
        if (!flag) {
          return false;
        }

        if (color.canUpdatePrice && color.unitPrice === 0) {
          var msg = this.getErrorMsg('unitPriceZero');
          this.$alert(msg, '信息');
          return false;
        }

        return true;
      },

      orderFilterMehod: function (options, queryValue) {
        if (queryValue === '') {
          return options;
        }

        queryValue = queryValue.toLowerCase();
        var filterParams = ['orderId', 'companyOrderId', 'factoryId', 'customerId'];
        options = _.filter(options, function (option) {
          for (var i = 0; i < filterParams.length; i++) {
            var filterParam = filterParams[i];
            var value = _.get(option, filterParam, '');
            if (value === null) {
              value = '';
            }
            if (typeof value === 'string') {
              value = value.toLowerCase();
            }
            if (value.indexOf(queryValue) !== -1) {
              return true;
            }
          }
          return false;
        });
        return options;
      },

      handleCountChange: function (color) {
        var valuationUint = color.valuationUint;
        if (valuationUint === '付') {
          color.valuationCount = color.count;
        }
      },

      getAllCount: function (colorList, color, field) {
        var totalCount = _.sumBy(colorList, function (obj) {
          if (!obj.checked) {
            return 0;
          }
          return obj[field];
        });
        color[field] = totalCount;
        return totalCount;
      },

      getErrorMsg: function (code) {
        var errorObj = {
          orderId: "请选择订单编号",
          supplierId: "请选择供应商",
          technology: "请选择加工工艺",
          maching: "请选择加工对象",
          color: "请选择返回颜色",
          count: "请输入返回颜色对应数量",
          valuationCount: "请输入返回颜色对应计价数量",
          unitPrice: "请输入单价",
          unitPriceZero: "单价不能为0"
        };
        return errorObj[code];
      }
    },
    components: {
      PageSelect: PageSelect
    },
    template: template
  };
}();
